import hashlib
# Create your views here.
import random

from django.http import JsonResponse
from django.shortcuts import render

from Bug.settings import *
from utils.tencent.sms import send_sms_single


def index(request):
    return render(request, "app01/index.html")


def mobile_phone(request):
    tpl = request.GET.get("tpl")  # 获得get请求的参数
    phone = request.GET.get("id_mobile_phone").strip()
    print(tpl, phone)
    # ************查数据库*****************8888
    x = get_phone(phone)
    if x:
        return send_sms(tpl, phone)
    else:

        return JsonResponse("此号码已经注册过!", safe=False)


from django.shortcuts import HttpResponse
from django_redis import get_redis_connection


def send_sms(tpl, phone):
    """"
    ？type=login
      type=register
      type=reset
    """
    # tpl = request.GET.get("tpl")  # 获得get请求的参数
    # mobile_phone= request.GET.get("id_mobile_phone").strip()
    template_id = TENCENT_SMS_TEMPLATE.get(tpl)  # 获取字典中名为tpl键的值
    if not template_id:
        return HttpResponse("模板不存在")
    code = random.randrange(1000, 9999)
    conn = get_redis_connection("default")

    if conn.get(phone):
        return  JsonResponse("注册太频繁!", safe=False)

    else:
        if len(phone)==11 :
            conn.set(phone, str(code), ex=65)

            value = conn.get(phone)
            print("正常获取Redis和状态，电话号码")
            print(value.decode("UTF-8"), tpl, phone)

            #res = send_sms_single(phone, template_id, [code, ])  # 注册码
            # #返回一个字典
            # print(res)
            # if res["result"] == 0:
            #     return HttpResponse("发送成功！！")
            # else:
            #     return HttpResponse(res["errmsg"])
            #
            return JsonResponse("验证码发送成功!", safe=False)
            # return HttpResponse("发送成功！！")

        else:
            return JsonResponse("手机号错误!", safe=False)


from django import forms
from app01 import models
from django.core.validators import RegexValidator


# 自动让表生成HTML
class RegisterModelForm(forms.ModelForm):
    # #mobile_phone=forms.EmailField(label="邮箱2")  将表中的字段名重命名
    # # 由于没有提供手机格式的校验，自己写一个正则表达式
    mobile_phone = forms.CharField(label="手机号", validators=[RegexValidator(r"1[35678]\d{9}", '手机号格式错误'), ])
    # 这个字段会走这个正则表达式
    password = forms.CharField(label="密码", widget=forms.PasswordInput())  # 根据widget插件展示

    confirm_password = forms.CharField(label="重复密码", widget=forms.PasswordInput())
    # # 没有这个label就添加一个，有就覆盖

    code = forms.CharField(label="验证码")  # 可以添加widget和validators插件

    # # 生成普通input标签

    class Meta:
        model = models.UserInfo
        # fields = "__all__"
        # 自定义字段顺序__all__是默认顺序
        fields = ["username", "email", "password", "confirm_password", "mobile_phone", "code"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():  # 变历字典，name是字段，field是对应的对象
            field.widget.attrs["class"] = 'form-control'
            field.widget.attrs["placeholder"] = "请输入合法的%s" % field.label


def register(requset):
    form = RegisterModelForm()
    return render(requset, 'app01/register.html', {"form": form})


def add_user(request):
    userinfo = []
    userr = {0: "用户名", 1: "密码", 2: "电话号码", 3: "邮箱"}
    userinfo.append(request.POST.get("username"))
    userinfo.append(request.POST.get("password"))
    userinfo.append(request.POST.get("mobile_phone"))
    userinfo.append(request.POST.get("email"))
    userinfo.append(request.POST.get("code"))

    conn = get_redis_connection("default")
    for key, value in userr.items():
        if userinfo[key]:
            if len(userinfo[key]) < 20:
                pass
            else:
                return JsonResponse(value + "太长", safe=False)
        else:
            return JsonResponse(value + "不能为空", safe=False)

    value = conn.get(userinfo[2])
    if get_email(userinfo[3]):
        try:
            print(value.decode("UTF-8"))
            if value.decode("UTF-8") == userinfo[4]:
               print("返回的结果是:",add_User(userinfo))
               return JsonResponse("注册成功", safe=False)

            else:
                return JsonResponse("验证码不正确！", safe=False)
        except AttributeError:
            return JsonResponse("没有验证码！", safe=False)
    else:
        return JsonResponse("邮箱已经被注册！", safe=False)




# 写入一条用户数据
def add_User(userinfo):
    # objects是类的控制器，由很多方法
    try:
        book_obj = models.UserInfo.objects.create(

            username=userinfo[0],
            password=hashlib.md5(userinfo[1].encode()).hexdigest(),
            mobile_phone=userinfo[2],
            email=userinfo[3],
        )
    except Exception as erro:
        return erro
    return book_obj


# 查询单条数据
def get_phone(phone):
    one = models.UserInfo.objects.filter(mobile_phone=phone)  # 查询一行数据
    print(one)

    if one:
        return False
    else:
        return True


def get_email(email):
    one = models.UserInfo.objects.filter(email=email)  # 查询一行数据

    if one:
        return False
    else:
        return True


def get_User(userinfo):
    one = models.UserInfo.objects.filter(username=userinfo[0], password=userinfo[1])  # 查询一行数据
    print(one)


def login_ui(request):
    return render(request,"app01/login.html")



from utils.captcha_image import *
def auth_code_port(request):
  """
  生成验证码的接口
  :param request:
  :return: 图片的对象
  """
  captcha_str, image_64 = Captcha_Get().get_captcha_image()
  #request.session['captcha_str'] = captcha_str #将验证码内容放入session以便于后边判断，但必须迁移数据库，否则报错
  #image = 'data:image/png;base64,'+image_64
  resp = HttpResponse(image_64, content_type='image/png')
  print(captcha_str)
  return resp